package com.changgou.search.controller;
import com.changgou.search.feign.SkuFeign;
import com.changgou.search.pojo.SkuInfo;
import com.changgou.util.Page;
import com.changgou.util.UrlUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import java.util.Map;

/*****
 * @Author: 黑马训练营
 * @Description: com.changgou.search.controller
 ****/
@Controller
@RequestMapping(value = "/search")
public class SkuController {

    @Autowired
    private SkuFeign skuFeign;

    /****
     * 搜索实现
     * Map searchMap:用户搜索的条件信息
     */
    @GetMapping(value = "/list")
    public String search(@RequestParam(required = false)Map searchMap, Model model){
        //调用feign搜索
        Map result = skuFeign.search(searchMap);

        //将数据存入到Model中
        model.addAttribute("result",result);

        //将搜索条件存入到model中用于页面回显
        model.addAttribute("searchMap",searchMap);

        //获取当前请求地址
        String url = url(searchMap);
        model.addAttribute("url",UrlUtils.replateUrlParameter(url,"pageNum"));
        //组装另外一个排序地址，不带有sortField和sortRule
        model.addAttribute("sorturl", UrlUtils.replateUrlParameter(url,"sortRule","sortField","pageNum"));

        //分页数据
        Page<SkuInfo> page = new Page<SkuInfo>(
                Long.valueOf(result.get("totalElements").toString()),
                Integer.parseInt(result.get("pageNum").toString()),
                Integer.parseInt(result.get("pageSize").toString()));
        model.addAttribute("page",page);
        return "search";
    }

    /***
     * 当前请求地址组装
     */
    public String url(Map<String,String> searchMap){
        //初始化地址  /search/list?key=value&key=value&key=value
        String url = "/search/list";

        if(searchMap!=null && searchMap.size()>0){
            url+="?";
            //循环Map，给url后面组装参数
            for (Map.Entry<String, String> entry : searchMap.entrySet()) {
                url+=entry.getKey()+"="+entry.getValue()+"&";
            }
            //去掉最后一个&
            url=url.substring(0,url.length()-1);
        }
        return url;
    }
}